<!--商品列表，可用优惠券商品列表、商品搜索列表使用-->
<script setup lang="ts">
import { linkNavigateTo } from '~/utils/util'
import { toRefs, computed, ref } from 'vue'
import { Mul } from '~/utils/util'
import useOrder from '~/composables/useOrder'
import { useUserStore } from '~/stores/user'
import { collectAddApi, collectCancelApi, cartAddApi, productDetailApi } from '~/server/goodsApi'
import feedback from '~/utils/feedback'
// 中文注释：新增 onGetCartCount 用于加入购物车后同步购物车数量
const { handlerProDetailLink, onGetCartCount } = useOrder()
const userStore = useUserStore()
const props = defineProps({
  //列表数据
  list: {
    type: Array,
    default: [],
  },
  //图片大小
  sizeData: {
    type: Object,
    default: {
      width: '228px',
      height: '228px',
    },
  },
})
const { list, sizeData } = toRefs(props)

// 中文注释：根据全局 collections 计算当前商品是否已选品
const isProductCollected = (productId: number) => {
  return userStore.collections ? userStore.collections.some((it: any) => it.productId === productId) : false
}

/**
 * 中文注释：加入购物车（悬浮面板点击）
 * 搜索/列表场景不做显式规格选择，默认数量为 1。若有规格，自动挑选一个有效规格
 */
const isAddingCartMap = ref<Record<number, boolean>>({})
// 中文注释：从商品规格值中挑选一个可用的规格（优先默认且有库存，其次任一有库存）
const pickValidSkuId = (productValueObj: Record<string, any>) => {
  const values = Object.values(productValueObj || {})
  if (!values.length) return 0
  const def = values.find((v: any) => v.isDefault && v.stock > 0)
  if (def) return def.id || 0
  const anyStock = values.find((v: any) => v.stock > 0)
  return (anyStock && anyStock.id) || 0
}
const handleAddCart = async (item: any, e?: Event) => {
  e?.stopPropagation?.()
  if (!userStore.isLogin) {
    feedback.msgWarning('请先登录')
    return
  }
  if (item?.stock === 0) {
    feedback.msgWarning('库存不足，无法加入购物车')
    return
  }
  const pid = item.id
  if (isAddingCartMap.value[pid]) return
  isAddingCartMap.value[pid] = true
  try {
    // 中文注释：加入购物车前查询商品详情，获取规格并选择一个可用规格
    const detailParams = { id: pid, marketingType: 0, type: 0 }
    const detail = await productDetailApi(detailParams as any)
    let productAttrUnique = 0
    if (detail && detail.productAttr && detail.productAttr.length && detail.productValue) {
      productAttrUnique = pickValidSkuId(detail.productValue)
      if (!productAttrUnique) {
        feedback.msgWarning('该商品规格暂无可用库存，请前往详情页选择')
        return
      }
    }
    await cartAddApi({ productId: pid, cartNum: 1, productAttrUnique })
    feedback.msgSuccess('添加购物车成功')
    onGetCartCount && onGetCartCount()
  } finally {
    isAddingCartMap.value[pid] = false
  }
}

// 中文注释：选品/取消选品（悬浮面板点击）
const isHandlingMap = ref<Record<number, boolean>>({})
const handleCollect = async (item: any, e?: Event) => {
  e?.stopPropagation?.()
  if (!userStore.isLogin) {
    feedback.msgWarning('请先登录')
    return
  }
  const pid = item.id
  if (isHandlingMap.value[pid]) return
  isHandlingMap.value[pid] = true
  try {
    if (isProductCollected(pid)) {
      await collectCancelApi({ ids: pid })
      const next = (userStore.collections || []).filter((x: any) => x.productId !== pid)
      userStore.setCollections(next)
      feedback.msgSuccess('取消成功')
    } else {
      await collectAddApi({ productId: pid, category: 0 })
      const next = [ ...((userStore.collections as any[]) || []), { productId: pid } ]
      userStore.setCollections(next)
      feedback.msgSuccess('选品成功')
    }
  } finally {
    isHandlingMap.value[pid] = false
  }
}

/**
 * 地址跳转
 */
const handlerNuxtLink = async (id: number) => {
  await handlerProDetailLink(id, 0)
  // await linkNavigateTo(`/product/detail/${id}`, { type: 'normal' })
}

// 跳入页面
const handleGoPage = (id) => {
  linkNavigateTo(`/merchant/merchant_home`, { merId: id })
}

const profitRate = (item: any) => {
  return ((item.price - item.cost) / item.cost * 100).toFixed(2)
}
</script>

<template>
  <div class="acea-row mt-20px">
    <div v-for="item in list" :key="item.id" class="mb15px item cursors">
      <div data-aos="fade-up" data-aos-anchor-placement="top-bottom" @click="handlerNuxtLink(item.id)">
        <div class="w228px borRadius overflow-hidden bg-#FFFFFF relative" :style="{ width: sizeData.width }">
          <!-- <div class="relative"> -->
            <div v-show="item.stock===0" class="sellOut">已售罄</div>
            <el-image
              class="backImg w228px h228px"
              :src="item.image"
              :style="{ width: sizeData.width, height: sizeData.height }"
            ></el-image>
            <div
              v-if="item.activityStyle"
              :style="{ backgroundImage: `url(${item.activityStyle})` }"
              class="border-picture backImg"
            ></div>
            <!-- 悬浮上滑内容区域：按钮左右结构（选品 / 加入购物车），统一选品背景色 -->
            <div class="hover-slide">
              <div class="hover-slide__row">
                <div class="hover-slide__btn" @click.stop="handleCollect(item, $event)">
                  <span
                    class="iconfont mr-6px"
                    :class="!isProductCollected(item.id) ? 'text-white icon-baobeishoucang' : 'text-yellow-50 icon-yishoucang'"
                  ></span>
                  <span
                    class="hover-slide__text"
                    :class="!isProductCollected(item.id) ? 'text-white' : 'text-yellow-50'"
                  >{{ isProductCollected(item.id) ? '取消选品' : '选品' }}</span>
                </div>
                <div class="hover-slide__btn" @click.stop="handleAddCart(item, $event)">
                  <span class="iconfont icon-gouwuche mr-6px"></span>
                  <span class="hover-slide__text">加入购物车</span>
                </div>
              </div>
            </div>
          <!-- </div> -->
          <div
            class="bg-white pt-15px pb-13px px-12px flex flex-justify-between"
            style="flex-direction: column; margin-top: -5px"
          >
            <svip-price :productPrice="item" :priceStyle="{ fontSize: '20px' }" class="mb-8px"></svip-price>
            <!--            <div class="text-12px font-color mb-8px font-500">-->
            <!--              <span class="oppoSans-M">￥</span-->
            <!--              ><span class="text-20px lh-20px font-600 dinProSemiBold">{{ item.price }}</span>-->
            <!--            </div>-->
            <div class="line2 text-14px fontColor333 mb-12px h-38px lh-19px acea-row">
              <div
                v-if="item.productTags && item.productTags.locationLeftTitle.length"
                class="inline-block text-12px bg-color text-#fff b-rd-2px py-2px mr-6px px-4px lh-12px"
              >
                {{ item.productTags.locationLeftTitle[0].tagName }}
              </div>
              {{ item.name }}
            </div>
            <!-- <div class="flex mb-10px h-16px">
              <div class="text-12px text-#999 mr-10px">
                <text v-if="Math.floor(item.replyNum) > 0">{{ item.replyNum }}条评论</text>
                <text v-if="item.replyNum === 0 || !item.replyNum">暂无评论</text>
                <text v-if="item.positiveRatio && Number(item.positiveRatio) > 0" class="ml-2px"
                  >好评{{ Mul(item.positiveRatio, 100) }}%</text
                >
              </div>
              <div class="text-12px text-#999">已售{{ item.sales }}{{ item.unitName }}</div>
            </div> -->
            <div v-if="item.productTags" class="h-20px mb-10px">
              <div v-if="item.productTags && item.productTags.locationUnderTitle.length" class="acea-row">
                <div
                  v-for="items in item.productTags.locationUnderTitle.length > 3
                    ? item.productTags.locationUnderTitle.slice(0, 3)
                    : item.productTags.locationUnderTitle"
                  :key="items.id"
                  class="text-12px lh-12px font-color base-border b-color-#E93323 b-rd-2px px3px py2px mr8px"
                >
                  {{ items.tagName }}
                </div>
              </div>
            </div>

            <div class="w-full mb-10px">
              <div class="text-12px text-#999 flex items-center leading-20px justify-between">
                <div>利润率：</div>
                <div class="text-red-500">{{ profitRate(item) }}%</div>
              </div>
              <div class="text-12px text-#999 flex items-center leading-20px justify-between">
                <div>零售价：</div>
                <div>￥{{ item.price }}</div>
              </div>
              <div class="text-12px text-#999 flex items-center leading-20px justify-between">
                <div>最低控价：</div>
                <div>￥{{ item.otPrice }}</div>
              </div>
            </div>

            <!-- <div class="cursors acea-row items-center" @click.stop="handleGoPage(item.merId)">
              <span class="iconfont icon-guanzhudianpu mr-5px text-12px font-color"></span>
              <span class="text-12px text-#666 line1 w-175px">{{ item.merName }}</span>
            </div> -->
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.item {
  margin-right: 15px;
  &:nth-child(5n) {
    margin-right: 0;
  }
}
/* 悬浮上滑面板样式（与商品卡片一致） */
.relative {
  position: relative;
  overflow: hidden;
}
.hover-slide {
  position: absolute;
  left: 0;
  right: 0;
  bottom: 0;
  transform: translateY(110%);
  transition: transform 0.25s ease;
  pointer-events: none;
}
.hover-slide__row {
  display: flex;
  pointer-events: all; /* 允许内部内容可点击 */
}
.hover-slide__btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 46px;
  background: #e93323; /* 与选品按钮相同背景色 */
  color: #fff;
  cursor: pointer;
}
.hover-slide__btn + .hover-slide__btn {
  /* 中文注释：左右按钮之间的分隔线 */
  border-left: 1px solid rgba(255, 255, 255, 0.2);
}
.hover-slide__text {
  font-size: 14px;
}
.item:hover .hover-slide {
  transform: translateY(0);
}
</style>
